package com.aizuda.boot.modules.third.wps.service;

import cn.hutool.core.collection.CollUtil;
import com.aizuda.boot.modules.file.service.FileInfoService;
import com.aizuda.boot.modules.third.wps.domain.entity.FileHistory;
import com.aizuda.boot.modules.third.wps.domain.vo.FileDownloadVo;
import com.aizuda.boot.modules.third.wps.domain.vo.FileInfoVo;
import com.aizuda.boot.modules.third.wps.enums.WebOfficeErrEnum;
import com.aizuda.boot.modules.third.wps.exception.WebOfficeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hjw
 * @description WebOffice 扩展功能接口
 * @date 2025年06月19日 17:07
 */
@Service
@Slf4j
public class ExtendCapacityService {
    @Value("${file.storage.local.download-url-prefix}")
    private String downloadUrlPrefix;

    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private FileHistoryService fileHistoryService;


    /**
     * 获取文件历史版本
     *
     * @param fileId 文件id
     * @param offset 列表偏移量
     * @param limit  单页最大长度
     * @return java.util.List<com.fim.keyaccount.fimai.aidb.third.wps.domain.vo.FileInfoVo>
     * @author hjw
     * @date 2025/6/19 17:09
     */
    public List<FileInfoVo> fileVersions(String fileId, int offset, int limit) {
        //根据文件id获取原始文件信息

        String lastSql = "limit " + offset + "," + limit;
        List<FileHistory> list = fileHistoryService.lambdaQuery()
                .eq(FileHistory::getFileId, fileId)
                .isNotNull(FileHistory::getVersion)
                .orderByDesc(FileHistory::getVersion)
                .last(lastSql)
                .list();
        if (CollUtil.isEmpty(list)) {
            throw new WebOfficeException(WebOfficeErrEnum.FILE_NOT_FOUND);
        }
        List<FileInfoVo> fileInfoVoList = new ArrayList<>(list.size());

        //转换为 FileInfoVo 列表
        list.forEach(fileHistory -> {
            fileInfoVoList.add(FileInfoVo.builder()
                    .id(fileHistory.getFileId().toString())
                    .name(fileHistory.getFileName())
                    .version(fileHistory.getVersion())
                    .size(fileHistory.getFileSize())
                    .createTime(fileHistory.getCreateTime().toInstant().getEpochSecond())
                    .modifyTime(fileHistory.getModifyTime().toInstant().getEpochSecond())
                    .creatorId(fileHistory.getCreatorId())
                    .modifierId(fileHistory.getModifierId())
                    .build())
            ;
        });


        return fileInfoVoList;
    }

    /**
     * 获取指定版本的文件信息
     *
     * @param fileId  文件id
     * @param version 版本号
     * @return com.fim.keyaccount.fimai.aidb.third.wps.domain.vo.FileInfoVo
     * @author hjw
     * @date 2025/6/19 17:10
     */
    public FileInfoVo fileVersion(String fileId, String version) {

        return fileHistoryService.lambdaQuery()
                .eq(FileHistory::getFileId, fileId)
                .eq(FileHistory::getVersion, version)
                .oneOpt()
                .map(fileHistory -> FileInfoVo.builder()
                        .id(fileHistory.getFileId().toString())
                        .name(fileHistory.getFileName())
                        .version(fileHistory.getVersion())
                        .size(fileHistory.getFileSize())
                        .createTime(fileHistory.getCreateTime().toInstant().getEpochSecond())
                        .modifyTime(fileHistory.getModifyTime().toInstant().getEpochSecond())
                        .creatorId(fileHistory.getCreatorId())
                        .modifierId(fileHistory.getModifierId())
                        .build()
                ).orElseThrow(() -> {
                    return new WebOfficeException(WebOfficeErrEnum.FILE_VERSION_NOT_FOUND);
                });
    }

    public FileDownloadVo fileVersionDownload(String fileId, String version) {

        return fileHistoryService.lambdaQuery()
                .eq(FileHistory::getFileId, fileId)
                .eq(FileHistory::getVersion, version)
                .last("limit 1")
                .oneOpt()
                .map(fileHistory ->
                        FileDownloadVo.builder()
                                .url(downloadUrlPrefix + "?fileKey=" + fileHistory.getFileKey())
                                .build()

                ).orElseThrow(() -> new WebOfficeException(WebOfficeErrEnum.FILE_VERSION_NOT_FOUND));

    }
}
